package com.javasm.commons;

import com.alibaba.fastjson.JSON;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class PhoneCaptchaAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    private String phoneParameter="phone";
    private String captchaParameter="captcha";

    public PhoneCaptchaAuthenticationFilter() {
        super(new AntPathRequestMatcher("/phone/login","POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (!request.getMethod().equals("POST"))throw new AuthenticationServiceException("请求方式有误: " + request.getMethod());
        if (!request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE))throw new AuthenticationServiceException("参数不是json" + request.getMethod());
        Map<String,String> map = JSON.parseObject(request.getInputStream(), Map.class);
        String phone = map.get(phoneParameter);
        String captcha = map.get(captchaParameter);
        if (phone==null)phone="";
        if (captcha==null)captcha="";
        phone.trim();
        PhoneCaptchaAuthenticationToken authRequest=new PhoneCaptchaAuthenticationToken(phone,captcha);
        this.setDetails(request,authRequest);
        return super.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request, PhoneCaptchaAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
}
